package com.tangyuan.ai.util;

import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.videoenhan20200320.Client;
import com.aliyun.videoenhan20200320.models.GetAsyncJobResultRequest;
import com.aliyun.videoenhan20200320.models.GetAsyncJobResultResponse;
import com.aliyun.videoenhan20200320.models.GetAsyncJobResultResponseBody;
import com.tangyuan.ai.entity.enums.AiExchangeStatusEnum;
import com.tangyuan.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class Sample {

    // 使用volatile关键字确保多线程环境下的可见性
    private static volatile Client clientInstance;

    @Value("${oss.accessKeyId:}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret:}")
    private String accessKeySecret;

    private static final String ENDPOINT = "videoenhan.cn-shanghai.aliyuncs.com";

    // 移除了静态修饰符，使用实例方法
    public Client getClient() throws Exception {
        if (clientInstance == null) {
            // 双重检查锁定中的同步块
            synchronized (Sample.class) {
                if (clientInstance == null) {
                    Config config = new Config()
                            .setAccessKeyId(accessKeyId)
                            .setAccessKeySecret(accessKeySecret)
                            .setEndpoint(ENDPOINT);
                    clientInstance = new Client(config);
                }
            }
        }
        return clientInstance;
    }

    public GetAsyncJobResultResponseBody.GetAsyncJobResultResponseBodyData getAsyncByJobId(String jobId) {
        GetAsyncJobResultResponseBody.GetAsyncJobResultResponseBodyData data = new GetAsyncJobResultResponseBody.GetAsyncJobResultResponseBodyData();
        try {
            // 使用getInstance方法获取Client实例
            Client client = getClient();
            GetAsyncJobResultRequest request = new GetAsyncJobResultRequest().setJobId(jobId);
            RuntimeOptions runtime = new RuntimeOptions();
            GetAsyncJobResultResponse options = client.getAsyncJobResultWithOptions(request, runtime);
            return options.getBody().getData();
        } catch (Exception e) {
            data.setStatus(AiExchangeStatusEnum.PROCESS_FAILED.getStatus());
            data.setErrorMessage(ResultCodeEnum.DATA_ERROR.getMessage());
            log.error("AI换脸异常,jobId:{},异常:",e.getMessage());
            return data;
        }
    }
}
